package com.mrd.gtimp.business.service;

import com.mrd.base.BaseBiz;
import com.mrd.exception.QueryException;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.business.entity.BaseBusinessModel;
import com.mrd.spring.repository.BaseRepository;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

@Service
public class BusinessModel extends BaseBiz<BaseBusinessModel> {


    public void saveBusinesses(List<? extends BaseBusinessModel> baseBusinessesModel) throws Exception {
        saveBusinesses(baseBusinessesModel, new ArrayList<List<String>>());
    }

    /*
     * (non-Javadoc)
     * @see com.mrd.gtimp.business.biz.BusinessModelBiz#saveBusinesses(java.util.List, java.util.List)
     */
    @SuppressWarnings({"unchecked", "rawtypes"})

    public void saveBusinesses(List<? extends BaseBusinessModel> baseBusinessModels,
                               List<List<String>> properties) throws Exception {
        WebApplicationContext wc = WebApplicationContextUtils
                .getWebApplicationContext(HttpUtils.getServletContext());
        int i = 0;
        for (BaseBusinessModel baseBusinessModel : baseBusinessModels) {
            // 获取注入的业务处理对象名如bookingBizImpl,spring中的名称第一个字母小写
            StringBuffer biz = new StringBuffer();
            String className = baseBusinessModel.getClass().getSimpleName();
            biz.append(Character.toLowerCase(className.charAt(0)));// 将起始字符换成小写
            biz.append(className.substring(1));// 添加其他内容
            biz.append("BizImpl");
            BaseBusinessModelBiz<BaseBusinessModel> businessModelBiz = (BaseBusinessModelBiz) wc.getBean(biz.toString());
            if (properties == null || properties.size() == 0) {
                businessModelBiz.saveBusiness(baseBusinessModel, null);
            } else {
                businessModelBiz.saveBusiness(baseBusinessModel, properties.get(i));
            }
            i++;
        }
    }

    @Resource
    @Qualifier("businessModelDao")
    public void setBaseRepository(BaseRepository<BaseBusinessModel, String> baseRepository) {
        super.baseRepository = baseRepository;
    }

    public boolean isExistModel(String model_name, String type) {
        String sql = "select * from T_BIZ_BASE_BUSINESS_MODEL where T_BIZ_BASE_BUSINESS_MODEL.Model_Name='" + model_name + "' and T_BIZ_BASE_BUSINESS_MODEL.type='" + type + "'";
        int count = 0;
        try {
            count = baseRepository.findEntityCountBySql(sql, null);
        } catch (QueryException e) {
            e.printStackTrace();
        }
        return count <= 0 ? false : true;
    }


}
